package configEntity

import (
	contractorm "github.com/goravel/framework/contracts/database/orm"
	"github.com/goravel/framework/database/orm"
	"github.com/goravel/framework/facades"
)

type ConfigTab struct {
	orm.Model
	PID           uint        `json:"pid" gorm:"column:pid" form:"pid"`                   // 上级分类id
	Title         string      `json:"title" gorm:"column:title" form:"title"`             // 配置分类名称
	EngTitle      string      `json:"eng_title" gorm:"column:eng_title" form:"eng_title"` // 配置分类英文名称
	Status        int64       `json:"status" gorm:"column:status" form:"status"`          // 配置分类状态
	Info          int64       `json:"info" gorm:"column:info" form:"info"`                // 配置分类是否显示
	Icon          string      `json:"icon" gorm:"column:icon" form:"icon"`                // 图标
	Type          int64       `json:"type" gorm:"column:type" form:"type"`                // 配置类型
	Sort          int64       `json:"sort" gorm:"column:sort" form:"sort"`                // 排序
	MenusID       int64       `json:"menus_id" gorm:"column:menus_id" form:"menus_id"`    // 菜单ID
	Children      []ConfigTab `json:"children" gorm:"foreignKey:pid;" form:"children"`    // 自关联
	SystemConfigs []Config    `json:"system_configs" gorm:"foreignKey:config_tab_id;references:id"`
	orm.SoftDeletes
}

// Tree 递归获取所有子类
func (s *ConfigTab) Tree() []ConfigTab {
	// 先查询顶层节点
	var topLevelTabs []ConfigTab
	ormInstance := facades.Orm().Query()
	if ormInstance == nil {
		panic("facades.Orm() returned nil")
	}
	ormInstance.Model(&ConfigTab{}).Where("pid = ?", 0).With("Children").Find(&topLevelTabs)

	// 递归构建子节点
	for i, tab := range topLevelTabs {
		topLevelTabs[i].Children = buildChildren(tab, ormInstance)
	}

	return topLevelTabs
}

// buildChildren 递归构建子节点
func buildChildren(parent ConfigTab, ins contractorm.Query) []ConfigTab {
	if ins == nil {
		panic("ins is nil")
	}
	var children []ConfigTab
	ins.Model(&ConfigTab{}).Where("pid = ?", parent.ID).With("Children").Find(&children)
	for i, child := range children {
		// 添加调试信息
		facades.Log().Infof("Processing child: %+v", child)
		children[i].Children = buildChildren(child, ins)
	}
	return children
}
